﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SearchProfileByBarcode.ascx.cs" company="VDC-IT" author="ltduc">
//   SearchProfile code behind
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace VDC.VONE.WEB.Modules.SearchProfileByBarcode.Controls
{
    #region

    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using System.Reflection;
    using System.Text;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using VDC.COMMON;
    using VDC.COMMON.ExceptionHelpers;
    using VDC.COMMON.NonPersistents;
    using VDC.VONE.BLL;
    using VDC.VONE.ENTITIES;

    #endregion

    /// <summary>
    /// Search Profile
    /// </summary>
    public partial class SearchProfileByBarcode : UserControl
    {
        #region Constants

        /// <summary>
        /// The NUMBER.
        /// </summary>
        private const string NUMBER = "lblSTT";

        /// <summary>
        ///     The edit
        /// </summary>
        private const string Edit = "Edit$";

        /// <summary>
        ///     The positions id
        /// </summary>
        private const string ProfileId = "ProfileId";
        
        /// <summary>
        ///     The Code
        /// </summary>
        private const string CODE = "Code";

        /// <summary>
        ///     Url Edit Position
        /// </summary>
        private const string UrlProfileEdit = "~/Modules/HoSo/GiaiquyetthutuchanhchinhEdit.aspx?ReturnUrl={0}&ProfileId={1}&PageIndex={2}";

        /// <summary>
        /// Const lblTinhTrang
        /// </summary>
        private const string LABLESTATUS = "lblTinhTrang";

        /// <summary>
        /// The imgopen
        /// </summary>
        private const string IMGOPEN = "imgOpen";

        /// <summary>
        /// The images vb open path
        /// </summary>
        private const string ImagesVbOpenPath = "../../../Images/vb_open.png";

        /// <summary>
        /// The images vb close path
        /// </summary>
        private const string ImagesVbClosePath = "../../../Images/vb_close.png";
        #endregion

        #region Fields

        /// <summary>
        ///     The mouse out
        /// </summary>
        private readonly string mouseOut =
            "this.style.backgroundColor=self.MouseOverOldColor; this.style.color='Black';";

        /// <summary>
        ///     The mouse over
        /// </summary>
        private readonly string mouseOver =
            "self.MouseOverOldColor=this.style.backgroundColor;this.style.color='#C04000';";

        /// <summary>
        ///     The number.
        /// </summary>
        private int number = 1;

        /// <summary>
        ///  Gets or sets list Id Of Profile separator by ;
        /// </summary>
        private StringBuilder ProfileIds
        {
            get
            {
                this.Session[Constants.SessionKey.SearchProfileByBarcode] = this.Session[Constants.SessionKey.SearchProfileByBarcode] ?? new StringBuilder();
                var strProifleId = (StringBuilder)this.Session[Constants.SessionKey.SearchProfileByBarcode];

                return strProifleId;
            }

            set 
            {
                this.Session[Constants.SessionKey.SearchProfileByBarcode] = value; 
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// The grv profile row data bound.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void GrvProfileRowDataBound(object sender, GridViewRowEventArgs e)
        {
            string methodName = MethodBase.GetCurrentMethod().DeclaringType.ToString() + Constants.Dot + MethodBase.GetCurrentMethod().Name;

            LogHelper.Instance.WriteInfo(Constants.Begin + methodName);
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    e.Row.Attributes[Constants.ClientEvent.MouseOver] = this.mouseOver;
                    e.Row.Attributes[Constants.ClientEvent.MouseOut] = this.mouseOut;
                    for (int i = 1; i < this.GrvProfile.Columns.Count - 1; i++)
                    {
                        e.Row.Cells[i].Attributes.Add(
                            Constants.ClientEvent.Click, this.Page.ClientScript.GetPostBackEventReference((GridView)sender, Edit + e.Row.RowIndex.ToString(CultureInfo.CurrentCulture)));
                    }

                    var lblStatus = e.Row.FindControl(LABLESTATUS) as Label;
                    var profile = e.Row.DataItem as ProfileEN;
                    var imgOpen = e.Row.FindControl(IMGOPEN) as Image;

                    if (profile != null && lblStatus != null && imgOpen != null)
                    {
                        var order = profile.AppointmentDate - DateTime.Now.Date;
                        var finaled = profile.ProfileStatusId > 0 &&
                                      profile.ProfileStatus.Code == Constants.ProfileStatus.KETTHUC;

                        if (order.HasValue && profile.AppointmentDate.HasValue)
                        {
                            int holidays = PublicFuncs.GetHolidaysBetween(profile.AppointmentDate.Value.Date, DateTime.Now.Date);
                            lblStatus.Text = PublicFuncs.GetStatus(finaled, order.Value.Days, holidays);
                        }

                        imgOpen.ImageUrl = profile.IsOpen ? ImagesVbOpenPath : ImagesVbClosePath;
                    }

                    var lblNumber = e.Row.FindControl(NUMBER) as Label;
                    lblNumber.Text = (this.number++).ToString();
                }

                LogHelper.Instance.WriteInfo(Constants.End + methodName);
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteError(methodName + Constants.Colon + ex.Message);
                ExceptionHandler.Instance.HandleUiException(ex);
            }
        }

        /// <summary>
        /// The GridView profile row editing.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void GrvProfileRowEditing(object sender, GridViewEditEventArgs e)
        {
            string methodName = MethodBase.GetCurrentMethod().DeclaringType.ToString() + Constants.Dot + MethodBase.GetCurrentMethod().Name;
            LogHelper.Instance.WriteInfo(Constants.Begin + methodName);
            try
            {
                if (this.GrvProfile.DataKeys[e.NewEditIndex].Values[ProfileId] != null)
                {
                    this.Session[Constants.SessionKey.UpdateStatusProfileKey] = true;
                    int profleId = Convert.ToInt32(this.GrvProfile.DataKeys[e.NewEditIndex].Values[ProfileId]);
                    UserService userService = new UserService();
                    var lstUsers = userService.GetUsersByProfileId(profleId);
                    var currentUserId = Convert.ToInt32(this.Session[Constants.SessionKey.CurrentUserId]);

                    if (lstUsers.Count(k => k.UserId == currentUserId) > 0)
                    {
                        this.Response.Redirect(string.Format(UrlProfileEdit, this.Request.Url.AbsolutePath, profleId, this.GrvProfile.PageIndex), false);
                        HttpContext.Current.ApplicationInstance.CompleteRequest();
                    }
                    else
                    {
                        var code = this.GrvProfile.DataKeys[e.NewEditIndex].Values[CODE];
                        this.lblMessage.Text = string.Format(PublicFuncs.GetMessage(Messages.MessageAccessProfileDenny), code);
                    }
                }

                LogHelper.Instance.WriteInfo(Constants.End + methodName);
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteError(methodName + Constants.Colon + ex.Message);
                ExceptionHandler.Instance.HandleUiException(ex);
            }
        }

        /// <summary>
        /// Handles the Init event of the Page control.
        /// </summary>
        /// <param name="sender">
        /// The source of the event.
        /// </param>
        /// <param name="e">
        /// The <see cref="EventArgs"/> instance containing the event data.
        /// </param>
        protected void Page_Init(object sender, EventArgs e)
        {
            this.GrvProfile.PageSize = this.Pager1.RecordsPerPage = PublicFuncs.PageSize;
        }

        /// <summary>
        /// The page_ load.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void Page_Load(object sender, EventArgs e)
        {
            string methodName = MethodBase.GetCurrentMethod().DeclaringType.ToString() + Constants.Dot + MethodBase.GetCurrentMethod().Name;
            LogHelper.Instance.WriteInfo(Constants.Begin + methodName);
            try
            {
                this.Pager1.DelegatePopulateData = this.Search;

                LogHelper.Instance.WriteInfo(Constants.End + methodName);
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteError(methodName + Constants.Colon + ex.Message);
                ExceptionHandler.Instance.HandleUiException(ex);
            }
        }

        /// <summary>
        /// Event Search_OnClick
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void BtnSearch_OnClick(object sender, EventArgs e)
        {
            string methodName = MethodBase.GetCurrentMethod().DeclaringType.ToString() + Constants.Dot + MethodBase.GetCurrentMethod().Name;
            LogHelper.Instance.WriteInfo(Constants.Begin + methodName);
            try
            {
                this.Pager1.Paging();

                LogHelper.Instance.WriteInfo(Constants.End + methodName);
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteError(methodName + Constants.Colon + ex.Message);
                ExceptionHandler.Instance.HandleUiException(ex);
            }
        }

        /// <summary>
        /// Event LbtDeleteAll_OnClick
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        protected void LbtDeleteAll_OnClick(object sender, EventArgs e)
        {
            string methodName = MethodBase.GetCurrentMethod().DeclaringType.ToString() + Constants.Dot + MethodBase.GetCurrentMethod().Name;
            LogHelper.Instance.WriteInfo(Constants.Begin + methodName);
            try
            {
                this.ProfileIds.Clear();
                this.Pager1.Paging();
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteError(methodName + Constants.Colon + ex.Message);
                ExceptionHandler.Instance.HandleUiException(ex);
            }
        }

        /// <summary>
        /// The Search Profile
        /// </summary>
        private void Search()
        {
             string methodName = MethodBase.GetCurrentMethod().DeclaringType.ToString() + Constants.Dot + MethodBase.GetCurrentMethod().Name;
            LogHelper.Instance.WriteInfo(Constants.Begin + methodName);
            try
            {
                this.pnlSearch.Visible = true;

                this.number = ((this.Pager1.PageIndex - 1) * this.GrvProfile.PageSize) + 1;
                var profileService = new ProfileService();

                var searchProfileNP = this.GetSearchProfileByInputs();

                if (!string.IsNullOrEmpty(searchProfileNP.Code))
                {
                    this.lblMessage.Text = string.Format(PublicFuncs.GetMessage(Messages.MessageSearchNotHasResult));

                    var lstProfileResult = profileService.GetProfileSearch(searchProfileNP);

                    var profileResult =
                        lstProfileResult.FirstOrDefault(
                            k => string.Compare(k.Code, searchProfileNP.Code, StringComparison.OrdinalIgnoreCase) == 0);

                    if (profileResult != null)
                    {
                        var profileIds = this.ProfileIds.ToString().Split(
                            new[]
                                {
                                    Constants.Semicolon
                                },
                            StringSplitOptions.RemoveEmptyEntries);

                        var strProfileIdResult = Convert.ToString(profileResult.ProfileId);
                        if (!profileIds.Contains(strProfileIdResult))
                        {
                            this.ProfileIds.Append(string.Format("{0}{1}", Constants.Semicolon, strProfileIdResult));
                            this.lblMessage.Text = string.Format(PublicFuncs.GetMessage(Messages.MessageSearchHasResult), 1);
                        }
                    }
                }

                searchProfileNP = this.GetSearchProfileBySession();
                IList<ProfileEN> lstProfile = new List<ProfileEN>();
                if (!string.IsNullOrEmpty(searchProfileNP.Ids))
                {
                    lstProfile = profileService.GetProfileByIds(searchProfileNP);
                }

                this.Pager1.TotalRecords = searchProfileNP.TotalRecords;
                this.lblCount.Text = searchProfileNP.TotalRecords.ToString(CultureInfo.CurrentCulture);
                this.GrvProfile.DataSource = lstProfile;
                this.GrvProfile.DataBind();

                this.lbtDeleteAll.Visible = searchProfileNP.TotalRecords > 0;
                this.txtCode.Text = string.Empty;
                this.txtCode.Focus();
               
                LogHelper.Instance.WriteInfo(Constants.End + methodName);
            }
            catch (Exception ex)
            {
                LogHelper.Instance.WriteError(methodName + Constants.Colon + ex.Message);
                ExceptionHandler.Instance.HandleUiException(ex);
            }
        }

        /// <summary>
        /// Get Search Profile By Input
        /// </summary>
        /// <returns>return SearchProfileNP</returns>
        private SearchProfileNP GetSearchProfileByInputs()
        {
            var searchProfileNP = new SearchProfileNP();

            if (!string.IsNullOrEmpty(this.txtCode.Text))
            {
                searchProfileNP.Code = this.txtCode.Text;
            }

            return searchProfileNP;
        }

        /// <summary>
        /// Get Search Profile By Session
        /// </summary>
        /// <returns>return SearchProfileNP</returns>
        private SearchProfileNP GetSearchProfileBySession()
        {
            var searchProfileNP = new SearchProfileNP();

            searchProfileNP.Ids = this.ProfileIds.ToString();
            searchProfileNP.Delimeter = Constants.Semicolon;

            searchProfileNP.PageIndex = this.Pager1.PageIndex;

            searchProfileNP.PageSize = this.Pager1.RecordsPerPage;

            return searchProfileNP;
        }

        #endregion
    }
}